type integert = gen i8|i16|i32|i64|u8|u16|u32|u64|int|uint
type floatert = gen float|f32|f64
type numbert = gen integert|floatert

fn ascii(string c):u8 {
    if c.len != 1 {
        throw 'c length must equal to 1'
    }
    var list = c as [u8]
    return list[0]
}

// 引用传递
fn reverse([numbert] list) {
    int start = 0
    int end = list.len - 1
    for start < end {
        (list[start], list[end]) = (list[end], list[start])
        start += 1
        end -= 1
    }
}

fn itos(integert i):string {
    return itos(i, '0', 0 as u8)
}

fn itos(integert i, string fill, u8 width):string {
    var base = 10
    var is_neg = false

    if i < 0 {
        is_neg = true
        i = -i // 转换为正数
    }

    var result = [] as [u8]

    if i == 0 {
        if width == 0 {
            return '0'
        }

        // 填充 width 个数的 0， 并返回
        for u8 i = 0; i < width; i+=1 {
            result.push(ascii(fill))
        }

        return result as string
    }


    // 按 base 进行转换
    for i != 0 {
        int rem = i as int % base
        result.push(rem as u8 + ascii('0') as u8)

        i = i / 10
    }

    u8 result_width = result.len as u8
    if is_neg {
        result_width += 1
    }

    if fill == ' ' {
        if is_neg {
            result.push(ascii('-'))
        }
        // 填充 ' '
        for width > result_width {
           result.push(ascii(fill))        
           result_width += 1
        } 
    } else {
        // fill == '0'
        for width > result_width {
           result.push(ascii(fill))        
           result_width += 1
        }

        if is_neg {
            result.push(ascii('-'))
        }
    }

    // 数组反转
    reverse(result)

    return result as string
}

fn ftos(floatert f):string {
    var is_neg = false
    if f < 0 {
        is_neg = true
        f = -f
    }

    // 取整数部分
    int int_part = f as int
    var int_str = itos(int_part)  // 将整数部分转换为字符串

    // 取小数部分
    var frac_part =  f - int_part as floatert

    var frac_str = ''

    if frac_part > 0 {
        frac_str = '.'
        var precision = 6  // 设置小数部分的精度

        // 将 frac_part 转换成整数(precision 位数)
        for int i = 0; i < precision; i+=1 {
            var digit = (frac_part * 10) as int
            frac_str += itos(digit)

            frac_part = (frac_part * 10) - digit as floatert
        }
    }

    if is_neg {
        return '-' + int_str + frac_str
    }
    
    return int_str + frac_str
}
